<template>
  <div class="back">
    <!-- 分类+搜索+新增+删除 -->
    <div class="header">
      <el-row>
        <el-button :type="nowType === null ? 'primary' : ''" size="mini" icon="el-icon-s-grid" round @click="typeChange(null)">全部</el-button>
        <el-button v-for="t in types" :key="t.type" :type="nowType === t.type ? 'primary' : ''" size="mini" :icon="t.icon" round @click="typeChange(t.type)">{{ t.typeName }}</el-button>
      </el-row>
      <br>
      <el-input v-model="searchName" placeholder="搜索设备名称" size="mini" clearable style="float: left; width: 15%; margin-right: 15px;" />
      <el-button type="primary" size="mini" @click="search">搜索</el-button>
      <el-button type="primary" size="mini" style="margin-right: 12px;" @click="handelClickAdd">添加+</el-button>
      <el-popover
        v-model="visible"
        placement="top"
        width="160"
      >
        <p>确定删除选中设备?</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="visible = false">取消</el-button>
          <el-button type="primary" size="mini" @click="deleteMachines">确定</el-button>
        </div>
        <el-button slot="reference" type="primary" size="mini">删除-</el-button>
      </el-popover>
      <el-button v-if="!isFull" size="mini" type="primary" icon="el-icon-arrow-left" style="float: right; margin-right: 5%;" @click="fullTable">完整列表</el-button>
    </div>
    <!-- 列表 -->
    <div class="body">
      <!-- <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox> -->
      <el-checkbox-group v-model="checkedMachines" @change="handleCheckedMachinesChange">
        <el-row>
          <el-col v-for="machine in machines" :key="machine.id" :span="5" style="margin-right: 4%;">
            <el-card :body-style="{ padding: '5px' }" style="margin-top: 15px;">
              <el-checkbox :key="machine.id" :label="machine.id" />{{ machine.id }}
              <el-dropdown style="float: right;">
                <i class="el-icon-more-outline" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleClickEdit(machine)">编辑</el-dropdown-item>
                  <el-dropdown-item @click.native="deleteMachine(machine.id)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <img :src="machine.img" class="image">
              <div style="padding: 14px;">
                <div v-if="types.length !== 0" class="producer">{{ types.find(t => t.type === machine.type).typeName }}</div>
                <div class="name">{{ machine.name }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </div>
    <!-- 新增表格 -->
    <el-dialog :title="isAdd ? '新增' : '编辑'" :visible.sync="dialogFormVisible">
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">
        <el-form-item class="add" label="设备名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="addForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item class="add" label="种类" prop="type">
          <el-select v-model="addForm.type" style="width: 100%;" placeholder="请选择种类" @change="getSubTypes(addForm.type)">
            <el-option v-for="t in types" :key="t.type" :label="t.typeName" :value="t.type" />
          </el-select>
        </el-form-item>
        <el-form-item class="add" label="设备" prop="subType">
          <el-select v-model="addForm.subType" style="width: 100%;" placeholder="请先选择设备种类" :disabled="subTypes.length === 0">
            <el-option v-for="t in subTypes" :key="t.subType" :label="t.subTypeName" :value="t.subType" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="isAdd" type="primary" @click="addMachine">确 定</el-button>
        <el-button v-else type="primary" @click="editMachine">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        :current-page.sync="page"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="totalCount"
        style="text-align: center; margin-top: 20px"
      />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: 1,
      pageSize: 8,
      totalCount: 0,
      searchName: '',
      types: [],
      icons: [
        'el-icon-coordinate',
        'el-icon-top',
        'el-icon-data-analysis',
        'el-icon-full-screen',
        'el-icon-monitor',
        'el-icon-menu',
        'el-icon-truck',
        'el-icon-c-scale-to-original',
        'el-icon-data-board',
        'el-icon-news'
      ],
      subTypes: [],
      nowType: null,
      condition: {
        name: '',
        type: '',
        subType: ''
      },
      dialogFormVisible: false,
      formLabelWidth: '100px',
      visible: false,
      addForm: {
        name: '',
        type: '',
        subType: ''
      },
      isAdd: true,
      isFull: true,
      isSearch: false,
      machines: [],
      checkAll: false,
      checkedMachines: [],
      isIndeterminate: false,
      rules: {
        name: [
          { required: true, message: '请输入设备名称', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择种类', trigger: 'change' }
        ],
        subType: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    page() {
      if (this.isSearch) {
        this.search()
      } else {
        this.getMachines()
      }
    }
  },
  mounted() {
    this.getMachines()
    this.getTypes()
  },
  methods: {
    getMachines() {
      this.axios.post(`http://139.9.77.245:8081/device/${this.page}/${this.pageSize}`, { type: this.nowType }, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.machines = res.data.data.records
          this.totalCount = res.data.data.total
          this.machines.forEach(machine => {
            machine.img = require('@/assets/machine/' + machine.subType + '.png')
          })
        }
      })
    },
    getTypes() {
      this.axios.get('http://139.9.77.245:8081/device-type').then(res => {
        if (res.data.code === 0) {
          this.types = res.data.data
          for (let i = 0; i < this.icons.length; i++) {
            this.types[i].icon = this.icons[i]
          }
        }
      })
    },
    getSubTypes(type) {
      this.axios.get(`http://139.9.77.245:8081/device-type/${type}`).then(res => {
        if (res.data.code === 0) {
          this.subTypes = res.data.data
        }
      })
    },
    handleCheckAllChange(val) {
      var checked = []
      this.machines.map((machine) => {
        checked.push(machine.id)
      })
      this.checkedMachines = val ? checked : []
      this.isIndeterminate = false
    },
    handleCheckedMachinesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.machines.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.machines.length
    },
    handleClickEdit(row) {
      this.isAdd = false
      this.addForm = row
      this.getSubTypes(this.addForm.type)
      this.dialogFormVisible = true
    },
    handelClickAdd() {
      this.isAdd = true
      this.addForm = {
        name: '',
        type: '',
        subType: ''
      }
      this.dialogFormVisible = true
    },
    addMachine() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.axios.post('http://139.9.77.245:8081/device', this.addForm).then(res => {
            if (res.data.code === 0) {
              this.getMachines()
              this.$message.success('添加成功')
              this.dialogFormVisible = false
              this.addForm = {
                name: '',
                type: '',
                subType: ''
              }
            } else {
              this.$message.error('添加失败')
            }
          })
        } else {
          console.log('提交失败')
          return false
        }
      })
    },
    editMachine() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.axios.put(`http://139.9.77.245:8081/device/${this.addForm.id}`, this.addForm).then(res => {
            if (res.data.code === 0) {
              this.getMachines()
              this.$message.success('修改成功')
              this.dialogFormVisible = false
              this.addForm = {
                name: '',
                type: '',
                subType: ''
              }
            }
            if (res.data.code === 1) {
              this.$message.error('修改失败')
            }
          })
        } else {
          console.log('修改失败')
          return false
        }
      })
    },
    deleteMachines() {
      this.axios.post('http://139.9.77.245:8081/device/deleteBatch', this.checkedMachines).then(res => {
        if (res.data.code === 0) {
          this.getMachines()
          this.$message.success('删除成功')
        }
        if (res.data.code === 1) {
          this.$message.error('删除失败')
        }
      })
      this.visible = false
    },
    deleteMachine(id) {
      this.$confirm('此操作将删除该设备相关信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete(`http://139.9.77.245:8081/device/${id}`).then(res => {
          if (res.data.code === 0) {
            this.getMachines()
            this.$message.success('删除成功')
          }
          if (res.data.code === 1) {
            this.$message.error('删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancel() {
      this.dialogFormVisible = false
      this.addForm = {
        name: '',
        type: '',
        subType: ''
      }
    },
    search() {
      this.axios.post(`http://139.9.77.245:8081/device/${this.page}/${this.pageSize}`, { name: this.searchName, type: this.nowType }, {
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.machines = res.data.data.records
          this.totalCount = res.data.data.total
          this.machines.forEach(machine => {
            machine.img = require('@/assets/machine/' + machine.subType + '.png')
          })
          this.isFull = false
          this.isSearch = true
        }
      })
    },
    fullTable() {
      this.page = 1
      this.nowType = null
      this.searchName = ''
      this.getMachines()
      this.isFull = true
      this.isSearch = false
    },
    typeChange(type) {
      this.nowType = type
      this.getMachines()
    }
  }
}
</script>

<style scoped>
.back{
  padding: 10px 15px;
  width: 100%;
  height: 100%;
  background-color: #eee;
}
.header{
  padding: 10px 10px 10px 10px;
  border-radius: 10px;
  background-color: #fff;
}
.body{
  margin-top: 15px;
  padding: 10px 10px 10px 45px;
  border-radius: 10px;
  background-color: #fff;
}
.image {
    width: 100%;
    height: auto;
    display: block;
  }
.producer {
    font-size: 10px;
    color: #999;
}
.name {
  margin-top: 5px;
  font-size: 15px;
}
.add {
  text-align: center;
  width: 100%;
}
</style>
